package com.shuzi.MediaShare.gui.login;

import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.shuzi.MediaShare.Constant;
import com.shuzi.MediaShare.R;
import com.shuzi.MediaShare.base.BaseFrameAtivity;
import com.shuzi.MediaShare.gui.home.HomePagerActvity;
import com.shuzi.MediaShare.model.LoginInfo;
import com.shuzi.MediaShare.net.Protocol;
import com.shuzi.MediaShare.net.UDPBoardCast;

/**
 * 
 * @author lung 下午10:45:50 2013
 */
public class LoginActivity extends BaseFrameAtivity
{

	/** 登陆信息 */
	private LoginInfo loginInfo = null;

	/** 发送获取ip的handler */
	private Handler handler = null;

	/** 获取ip成功 */
	public final static int SUCCESS_GET_IP = 1;

	/** 获取ip失败 */
	public final static int FAILED_GET_IP = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		loadingView.setVisibility(View.GONE);
		setShowErrorView(false);
		setTitleBarVisible(false);
		initHandler();

		UDPBoardCast.getInstance().sentBoardCast(handler);

	}

	private void initHandler()
	{
		handler = new Handler()
		{
			@Override
			public void dispatchMessage(Message msg)
			{
				super.dispatchMessage(msg);
				if (msg.what == SUCCESS_GET_IP)
				{
					Protocol.setUrl();
					Constant.isLogin = true;
					loadData();
				} else
				{
					if (!Constant.isLogin)
					{
						Toast.makeText(LoginActivity.this, "登陆失败，请检查网络",
								Toast.LENGTH_SHORT).show();
						loadingView.setVisibility(View.GONE);
						errorView.setVisibility(View.VISIBLE);
					}

				}

			}
		};

	}

	@Override
	protected boolean initData(Integer... params)
	{

		long firstTime = System.currentTimeMillis();
		loginInfo = Protocol.login();
		while (System.currentTimeMillis() - firstTime < 1500)
		{

		}

		return loginInfo != null;
	}

	@Override
	protected void refreshView(boolean isSuccessful, Integer... params)
	{
		if (isSuccessful)
		{
			if (!loginInfo.getCode().equals("0"))
			{
				Toast.makeText(LoginActivity.this, loginInfo.getMsg(),
						Toast.LENGTH_SHORT).show();
			} else
			{
				Intent intent = new Intent();
				intent.setClass(LoginActivity.this, HomePagerActvity.class);
				startActivity(intent);
			}
		} else
		{
			Toast.makeText(LoginActivity.this, "登陆失败，请检查网络", Toast.LENGTH_SHORT)
					.show();
		}
		finish();
	}

	@Override
	protected void tryAgain()
	{
		UDPBoardCast.getInstance().sentBoardCast(handler);
	}

	@Override
	protected View setCenterView()
	{
		return View.inflate(this, R.layout.login, null);
	}

}
